package com.jams.goodox.activity.login;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.bumptech.glide.Glide;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.activity.qa.ClassLearningActivity;
import com.jams.goodox.activity.qa.GlideCircleTransform;
import com.jams.goodox.activity.qa.entity.CourseData;
import com.jams.goodox.activity.qa.entity.Teacher;
import com.jams.goodox.activity.qa.parent.UploadQuestionActivity;
import com.jams.goodox.adapter.lfadapter.CommonRecycleViewAdapter;
import com.jams.goodox.adapter.lfadapter.LFRecyclerViewHolder;
import com.jams.goodox.listen.MyOnClickListener;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.widget.EditTextWithDel;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import me.leefeng.lfrecyclerview.OnItemClickListener;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 *  搜索课程
 * @author HP
 */
public class CourseSearchActivity extends BaseActivity implements View.OnClickListener,
        OnItemClickListener, LFRecyclerView.LFRecyclerViewListener,
        LFRecyclerView.LFRecyclerViewScrollChange{

    private static final String TAG = CourseSearchActivity.class.getSimpleName();
    @Bind(R.id.et_search_comm)
    EditTextWithDel et_search_comm;

    @Bind(R.id.tv_search)
    TextView tv_search;

    @Bind(R.id.lv_search_list)
    LFRecyclerView recyclerView;


    @Bind(R.id.all_layout)
    FrameLayout all_layout;

    private String keyword = "\"\"";//搜索关键字

    private CommonRecycleViewAdapter pAdapter;
    private List<CourseData> list = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.comm_search;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "课程搜索");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_theme));//沉侵式头部
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                /**隐藏软键盘**/
                View view = getWindow().peekDecorView();
                if (view != null) {
                    InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                return false;
            }
        });

        recyclerView.setLoadMore(false);
        recyclerView.setRefresh(false);
        recyclerView.setNoDateShow();
        recyclerView.setAutoLoadMore(false);
        recyclerView.setOnItemClickListener(this);
        recyclerView.setLFRecyclerViewListener(this);
        recyclerView.setScrollChangeListener(this);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        pAdapter = new CommonRecycleViewAdapter(recyclerView, list, R.layout.classroom_item) {
            @Override
            public void bindConvert(LFRecyclerViewHolder holder, int position, Object item, boolean isScrolling) {

                CourseData classRoomBean = list.get(position);
                holder.setText(R.id.title,classRoomBean.getTitle());
                holder.setText(R.id.price,"¥"+classRoomBean.getPrice());
                holder.setText(R.id.nickName,classRoomBean.getNickName());
                holder.setText(R.id.content,classRoomBean.getContent());
                holder.loadImage(R.id.imageView,classRoomBean.getImgPath());

                //Glide.with(context).load(classRoomBean.getImgPath()).into(holder.imageView);
                /*Glide.with(CourseSearchActivity.this).load(classRoomBean.getImgPath())
                        .placeholder(R.drawable.loading) //占位符 也就是加载中的图片，可放个gif
                        .error(R.mipmap.morentouxiang60) //失败图片
                        .bitmapTransform(new GlideCircleTransform(CourseSearchActivity.this))
                        .crossFade(1000).into();*/
            }
        };

        recyclerView.setAdapter(pAdapter);

        //tv_search.setOnClickListener(new MyOnClickListener(this));
        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchComm();
            }
        });
        et_search_comm.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchComm();
                }
                return false;
            }
        });

        /*et_search_comm.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchComm();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {  }

            @Override
            public void afterTextChanged(Editable s) {  }
        });*/

    }

    /**
     * 搜索问题
     */
    protected void searchComm() {
        clearMap();
        if(!TextUtils.isEmpty(et_search_comm.getText())){
            keyword = et_search_comm.getText().toString();
            Log.d(TAG, "  keyword= " + keyword);
        }

        StringBuilder pData = new StringBuilder();
        pData.append("pageNum:" + 0)
                .append(",pageSize:" + 10)
                .append(",keyword:" + keyword);

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);

        Log.d(TAG, " data strEntity= " + strEntity);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);

        Call<ResponseBody> example = createCallService(LoginService.class).courseSearch(body);

        showLoading();
        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                list.clear();
                try {
                    String data = response.body().string();
                    Log.d(TAG, " data courseSearch= " + data);
                    JSONObject jsonObject = new JSONObject(data);
                    if (200 == jsonObject.getInt("code")) {
                        misLoading();
                        String responseData = jsonObject.getString("responseData");
                        JSONArray jsonArray = new JSONArray(responseData);
                        if (null == jsonArray || jsonArray.length() <= 0) {
                            ToastUtil.show("列表数据为空");
                            return;
                        }

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            CourseData courseData = new CourseData();
                            courseData.setImgPath(object.getString("imgPath"));
                            courseData.setRadioLink(object.getString("radioLink"));
                            courseData.setTitle(object.getString("title"));
                            courseData.setNickName(object.getString("nickName"));
                            courseData.setCourseId(object.getInt("courseId"));
                            courseData.setPrice(object.getDouble("price"));
                            courseData.setContent(object.getString("descr"));

                            list.add(courseData);
                            Log.d(TAG, "courseData = " + courseData.toString());
                        }

                        pAdapter.notifyDataSetChanged();

                    } else {
                        ToastUtil.show("网络异常！");
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG, "onFailure = " + t.getMessage());
            }
        });
    }

    // 点击屏幕 关闭输入弹出框
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        /**隐藏软键盘**/
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void onClick(View v) {
        if (Utils.isFastDoubleClick())
            return;
        switch (v.getId()) {
            case R.id.tv_search:
                finish();
                break;
        }
    }



    @Override
    public void onRecyclerViewScrollChange(View view, int i, int i1) {

    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onClick(int position) {
        Log.d(TAG,"-----onClick--------" + position);
        Intent intent = new Intent(this,ClassLearningActivity.class);
        intent.putExtra("courseId",list.get(position).getCourseId());
        intent.putExtra("imagePath",list.get(position).getImgPath());
        intent.putExtra("nickName",list.get(position).getNickName());
        if(list.get(position).getPrice() <= 0){
            intent.putExtra("canShare",true);
        }else {
            intent.putExtra("canShare",false);
        }
        startActivity(intent);
    }

    @Override
    public void onLongClick(int po) {

    }

}
